// 图片上传服务层
// @author likai

package service

import (
	"admin-go-api/common/config"
	"admin-go-api/common/result"
	"admin-go-api/common/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"path"
	"strconv"
	"time"
)

type IUploadService interface {
	Upload(c *gin.Context)
}

type UploadServiceImpl struct {
}

// Upload 图片上传
func (u UploadServiceImpl) Upload(c *gin.Context) {
	// 获取上传的文件
	file, err := c.FormFile("file")
	if err != nil {
		result.Failed(c, int(result.ApiCode.FILEUPLOADERROR), result.ApiCode.GetMessage(result.ApiCode.FILEUPLOADERROR))
	}
	now := time.Now()
	// 获取上传文件的扩展名
	ext := path.Ext(file.Filename)
	// 按当前9位数纳秒给文件命名
	fileName := strconv.Itoa(now.Nanosecond()) + ext
	// 按 config里的UploadDir-年-月-日 指定目录名称
	filePath := fmt.Sprintf("%s%s",
		config.Config.ImageSettings.UploadDir,
		now.Format("2006-01-02"))
	// 创建目录
	util.CreateDir(filePath)
	// 目录+文件名
	fullPath := filePath + "/" + fileName
	// 将获取的上传文件按照fullPath 存储在服务器
	c.SaveUploadedFile(file, fullPath)

	result.Success(c, config.Config.ImageSettings.ImageHost+fullPath)
}

var uploadService = UploadServiceImpl{}

func UploadService() IUploadService {
	return &uploadService
}
